package com.middlegroup.pay.config;

import com.middlegroup.common.enums.ConfigKeyEnums;
import com.middlegroup.common.enums.ServiceType;
import com.middlegroup.pay.service.SystemCfgService;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.OAuthTokenCredential;
import com.paypal.base.rest.PayPalRESTException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by liguangcun on 2019/8/5.
 */
@Configuration
@Service
public class PaypalConfig {
    @Resource
    private SystemCfgService systemCfgService;
    @Bean
    public Map<String, String> paypalSdkConfig(){
        Map<String, String> sdkConfig = new HashMap<>();
        String mode=systemCfgService.getConfigString(ServiceType.paypal.getCode(), ConfigKeyEnums.mode.getName());
        sdkConfig.put("mode", mode);
        return sdkConfig;
    }

    @Bean
    public OAuthTokenCredential authTokenCredential(){
        String clientId=systemCfgService.getConfigString(ServiceType.paypal.getCode(), ConfigKeyEnums.clientId.getName());
        String clientSecret=systemCfgService.getConfigString(ServiceType.paypal.getCode(), ConfigKeyEnums.clientSecret.getName());
        return new OAuthTokenCredential(clientId, clientSecret, paypalSdkConfig());
    }

    @Bean
    public APIContext apiContext() throws PayPalRESTException{
        APIContext apiContext = new APIContext(authTokenCredential().getAccessToken());
        apiContext.setConfigurationMap(paypalSdkConfig());
        return apiContext;
    }
}
